#!/usr/bin/env python

import codecs
import re

class Table:
    """表示数据库中的一个表"""

    def __init__(self, table_name):
        self.table_name = table_name
        self.fields=[]
        self.fields_set_name=[]
        self.fields_statements=[]
        self.fields_type = []
        self.fields_type_cursor = []

    def add_field(self, fields_options):
        field_name = fields_options[1]
        field_type = fields_options[0]
        field_sqlite = self._generate_sql_by_type(field_type)
        if len(fields_options) == 3:
            field_sqlite += " " + fields_options[2]
        self.fields.append(field_name)
        
        self.fields_type.append(field_type)
        self.fields_type_cursor.append(self._generate_cursor_post_fix(field_type))
        self.fields_statements.append(field_sqlite + ",")

    def add_comma(self):
        self.fields_statements[-1] = self.fields_statements[-1][:-1]

    def title(self, word):
        return word[0].upper() + word[1:]

    def int_to_bool(self, index):
        if self.fields_type[index].lower() == 'boolean':
            return ' != 0'
        else:
            return ""

    def bool_to_int(self, index):
        if self.fields_type[index].lower() == 'boolean':
            return ' ? 1 : 0'
        else:
            return ""

    def _generate_cursor_post_fix(self, field_type):
        cursor_post_fix_dict = {
            'int':'Int',
            'boolean':'Int',
            'string' : 'String',
            'long': 'Long'
        }
        return cursor_post_fix_dict[field_type.lower()]

    def _generate_sql_by_type(self, field_type):
        type_sqlite_statements = {
            'int' : "INTEGER",
            'boolean': "INTEGER",
            'string' : "TEXT",
            'long'   : "INTEGER"
        }
        return type_sqlite_statements[field_type.lower()]

    def __str__(self):
        return str(self.fields_statements)

class DaoGenerator:
    """ 简单的数据库生成Python代码 """

    def __init__(self, entity_file_path):
        self.entity_file_path = entity_file_path

    def parse(self):
        print("DaoGenerator, file ", self.entity_file_path, " start to parse...")
        with codecs.open(self.entity_file_path, encoding='utf-8') as input_file:
            is_in_field_stock = False
            table = Table(self.entity_file_path[self.entity_file_path.rfind('/') + 1:-5])
            print(str(table.table_name))
            for line in input_file:
                line = line.strip()
                if len(line) == 0:
                    continue
                if line.startswith('//;;; start'):
                    is_in_field_stock = True
                    continue
                elif line.startswith('//;;; end'):
                    is_in_field_stock = False
                    break
                elif line.startswith('//'):
                    continue
                elif is_in_field_stock:
                    colon_index = line.find(';')
                    state_ment = line[:colon_index]
                    state_ment_list = re.split('\W+', state_ment)
                    special_orders = re.search(r'/\*;\((.*)\);\*/', line[colon_index:])
                    if special_orders:
                        state_ment_list.append(special_orders.group(1))

                    table.add_field(state_ment_list[1:])

            print(str(table))
            table.add_comma()
            return table


if __name__ == '__main__':

    
    generateObjectPath = '../java/ldk/easytouch/example/helper/SQLiteHelper.java'
    print("Start...")
    import os
    entity_path = '../java/ldk/easytouch/example/Entity/'
    file_list = os.listdir(entity_path)
    tables = []
    for file_name in file_list:
        if file_name.endswith('~'):
            continue
        
        print(file_name)
        generator = DaoGenerator(entity_path + file_name)
        table = generator.parse()
        tables.append(table)
        
    from tornado import template
    output_file = open(generateObjectPath, 'wb')
    loader = template.Loader("./")
    output_file.write(loader.load("SQLiteHelperTemplate").generate(tables=tables))

